import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../data/models/wiki_config.dart';
import '../../../data/models/favorite.dart';
import '../../../data/models/browse_history.dart';
import '../../../data/repositories/wiki_repository.dart';
import '../../../data/services/search_service.dart';
import '../../../data/services/database_service.dart';
import '../../../config/app_constants.dart';
import '../../../utils/storage_service.dart';
import '../../main_screen/controllers/main_screen_controller.dart';

class CategoryController extends GetxController {
  final WikiRepository _wikiRepository = WikiRepository();
  final SearchService _searchService = SearchService();
  final DatabaseService _databaseService = DatabaseService();
  late StorageService _storageService;
  
  // 收藏列表
  final RxList<Favorite> favorites = <Favorite>[].obs;
  
  // 浏览历史
  final RxList<BrowseHistory> browseHistory = <BrowseHistory>[].obs;
  
  // 当前分类
  final RxString currentCategory = ''.obs;
  
  // 分类列表
  final RxList<String> categories = <String>[].obs;
  
  // 热门站点
  final RxList<WikiItem> popularSites = <WikiItem>[].obs;
  
  // 热门站点别名
  RxList<WikiItem> get popularWikis => popularSites;
  
  // 当前选中的分类
  final Rx<String?> selectedCategory = Rx<String?>(null);

  // 搜索控制器
  final TextEditingController searchController = TextEditingController();
  
  // 所有Wiki站点
  final RxList<WikiItem> allWikiSites = <WikiItem>[].obs;
  
  // 过滤后的Wiki站点
  final RxList<WikiItem> filteredWikiSites = <WikiItem>[].obs;
  
  // 加载状态
  final RxBool isLoading = false.obs;
  
  // 错误状态
  final RxBool hasError = false.obs;
  final RxString errorMessage = ''.obs;
  
  // 搜索关键词
  final RxString searchQuery = ''.obs;
  
  // 当前选中的字母
  final RxString selectedLetter = ''.obs;
  
  // 字母索引列表
  final RxList<String> alphabetList = AppConstants.alphabetList.obs;
  
  // 搜索历史
  final RxList<String> searchHistory = <String>[].obs;
  
  // 是否显示搜索历史
  final RxBool showSearchHistory = false.obs;

  // 获取主屏幕控制器
  MainScreenController get mainController => Get.find<MainScreenController>();

  @override
  void onInit() {
    super.onInit();
    _initializeStorage();
    _initializeDatabase();
    _loadWikiSites();
    _loadSearchHistory();
    _loadFavorites();
    _loadBrowseHistory();
    _loadCategories();
    _loadPopularSites();
    
    // 监听搜索输入
    searchController.addListener(_onSearchChanged);
  }

  @override
  void onClose() {
    searchController.dispose();
    super.onClose();
  }

  // 初始化存储服务
  Future<void> _initializeStorage() async {
    _storageService = await StorageService.getInstance();
  }
  
  // 初始化数据库
  Future<void> _initializeDatabase() async {
    await _databaseService.initDatabase();
  }

  // 加载Wiki站点列表
  Future<void> _loadWikiSites() async {
    try {
      isLoading.value = true;
      hasError.value = false;
      
      final sites = await _wikiRepository.getAllWikiSites();
      allWikiSites.value = sites;
      filteredWikiSites.value = sites;
      
      // 按名称排序
      _sortWikiSites();
      
    } catch (e) {
      hasError.value = true;
      errorMessage.value = '加载Wiki列表失败: $e';
      print('Error loading wiki sites: $e');
    } finally {
      isLoading.value = false;
    }
  }

  // 加载搜索历史
  Future<void> _loadSearchHistory() async {
    try {
      await _initializeStorage();
      searchHistory.value = _storageService.getSearchHistory();
    } catch (e) {
      print('Error loading search history: $e');
    }
  }

  // 搜索输入变化
  void _onSearchChanged() {
    final query = searchController.text.trim();
    searchQuery.value = query;
    
    if (query.isEmpty) {
      showSearchHistory.value = false;
      filteredWikiSites.value = allWikiSites;
      selectedLetter.value = '';
    } else {
      showSearchHistory.value = true;
      _filterWikiSites(query);
    }
  }

  // 过滤Wiki站点 - 使用新的搜索服务
  Future<void> _filterWikiSites(String query) async {
    if (query.isEmpty) {
      filteredWikiSites.value = allWikiSites;
      return;
    }
    
    try {
      final filtered = await _searchService.searchWikiSites(query);
      filteredWikiSites.value = filtered;
    } catch (e) {
      print('Error filtering wiki sites: $e');
      // 降级到本地搜索
      final filtered = allWikiSites.where((site) {
        return site.name.toLowerCase().contains(query.toLowerCase()) ||
               site.description.toLowerCase().contains(query.toLowerCase()) ||
               (site.nameCn?.toLowerCase().contains(query.toLowerCase()) ?? false) ||
               (site.nameEn?.toLowerCase().contains(query.toLowerCase()) ?? false);
      }).toList();
      
      filteredWikiSites.value = filtered;
    }
  }

  // 按字母过滤
  void filterByLetter(String letter) {
    selectedLetter.value = letter;
    searchController.clear();
    showSearchHistory.value = false;
    
    final filtered = allWikiSites.where((site) {
      return site.category.toUpperCase() == letter.toUpperCase() ||
             site.name.toUpperCase().startsWith(letter.toUpperCase()) ||
             (site.nameCn?.toUpperCase().startsWith(letter.toUpperCase()) ?? false) ||
             (site.nameEn?.toUpperCase().startsWith(letter.toUpperCase()) ?? false);
    }).toList();
    
    filteredWikiSites.value = filtered;
  }

  // 清除过滤
  void clearFilter() {
    selectedLetter.value = '';
    searchController.clear();
    showSearchHistory.value = false;
    filteredWikiSites.value = allWikiSites;
  }

  // 执行搜索
  Future<void> performSearch(String query) async {
    if (query.trim().isEmpty) return;
    
    try {
      // 保存搜索历史
      await _storageService.addSearchHistory(query);
      await _loadSearchHistory();
      
      // 执行搜索
      searchController.text = query;
      showSearchHistory.value = false;
      await _filterWikiSites(query);
      
    } catch (e) {
      print('Error performing search: $e');
    }
  }

  // 选择Wiki站点
  Future<void> selectWikiSite(WikiItem wikiSite) async {
    try {
      // 添加到浏览历史
      await _addToBrowseHistory(wikiSite);
      
      // 通过主控制器切换Wiki站点
      await mainController.switchWikiSite(wikiSite);
      
      // 清除搜索状态
      searchController.clear();
      showSearchHistory.value = false;
      
    } catch (e) {
      print('Error selecting wiki site: $e');
      Get.snackbar(
        '选择失败',
        '无法选择 ${wikiSite.name}，请稍后重试',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 3),
      );
    }
  }

  // 刷新Wiki列表
  Future<void> refreshWikiSites() async {
    await _loadWikiSites();
  }

  // 刷新Wiki列表 (别名方法)
  Future<void> refreshWikiList() async {
    await refreshWikiSites();
  }

  // 清除搜索历史
  Future<void> clearSearchHistory() async {
    try {
      await _storageService.clearSearchHistory();
      searchHistory.clear();
      Get.snackbar(
        '清除成功',
        '搜索历史已清除',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      print('Error clearing search history: $e');
    }
  }

  // 移除单个搜索历史项
  Future<void> removeSearchHistory(String historyItem) async {
    try {
      await _storageService.removeSearchHistory(historyItem);
      searchHistory.remove(historyItem);
    } catch (e) {
      print('Error removing search history item: $e');
    }
  }
  
  // 按分类过滤
  void filterByCategory(String? category) {
    selectedCategory.value = category;
    searchController.clear();
    showSearchHistory.value = false;
    
    if (category == null || category.isEmpty) {
      filteredWikiSites.value = allWikiSites;
    } else {
      final filtered = allWikiSites.where((site) {
        return site.category.toLowerCase() == category.toLowerCase();
      }).toList();
      filteredWikiSites.value = filtered;
    }
  }

  // 排序Wiki站点
  void _sortWikiSites() {
    allWikiSites.sort((a, b) => a.name.compareTo(b.name));
    filteredWikiSites.sort((a, b) => a.name.compareTo(b.name));
  }

  // 获取指定字母的Wiki数量
  int getWikiCountForLetter(String letter) {
    return allWikiSites.where((site) {
      return site.category.toUpperCase() == letter.toUpperCase() ||
             site.name.toUpperCase().startsWith(letter.toUpperCase());
    }).length;
  }

  // 检查是否有搜索结果
  bool get hasSearchResults => filteredWikiSites.isNotEmpty;

  // 检查是否正在搜索
  bool get isSearching => searchQuery.value.isNotEmpty;

  // 检查是否选中了字母
  bool get hasSelectedLetter => selectedLetter.value.isNotEmpty;
  
  // 加载收藏列表
  Future<void> _loadFavorites() async {
    try {
      final favoriteList = await _databaseService.getAllFavorites();
      favorites.value = favoriteList;
    } catch (e) {
      print('Error loading favorites: $e');
    }
  }
  
  // 加载浏览历史
  Future<void> _loadBrowseHistory() async {
    try {
      final historyList = await _databaseService.getBrowseHistory(limit: 20);
      browseHistory.value = historyList;
    } catch (e) {
      print('Error loading browse history: $e');
    }
  }
  
  // 加载分类列表
  Future<void> _loadCategories() async {
    try {
      final categoryList = await _searchService.getCategories();
      categories.value = categoryList;
    } catch (e) {
      print('Error loading categories: $e');
    }
  }
  
  // 加载热门站点
  Future<void> _loadPopularSites() async {
    try {
      final popular = await _searchService.getPopularWikiSites(limit: 10);
      popularSites.value = popular;
    } catch (e) {
      print('Error loading popular sites: $e');
    }
  }
  
  // 添加到浏览历史
  Future<void> _addToBrowseHistory(WikiItem wikiSite) async {
    try {
      final history = BrowseHistory(
        wikiId: wikiSite.id,
        wikiName: wikiSite.name,
        wikiUrl: wikiSite.url,
        title: wikiSite.name,
        description: wikiSite.description,
        iconUrl: wikiSite.icon,
        createdAt: DateTime.now(),
        lastVisitAt: DateTime.now(),
        visitCount: 1,
      );
      
      await _databaseService.addOrUpdateHistory(history);
      await _loadBrowseHistory();
    } catch (e) {
      print('Error adding to browse history: $e');
    }
  }
  
  // 切换收藏状态
  Future<void> toggleFavorite(WikiItem wikiSite) async {
    try {
      final isFavorited = favorites.any((fav) => fav.wikiId == wikiSite.id);
      
      if (isFavorited) {
        await _databaseService.removeFavorite(wikiSite.id, wikiSite.url);
        Get.snackbar(
          '取消收藏',
          '已从收藏中移除 ${wikiSite.name}',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
      } else {
        final favorite = Favorite(
          wikiId: wikiSite.id,
          wikiName: wikiSite.name,
          wikiUrl: wikiSite.url,
          title: wikiSite.name,
          description: wikiSite.description,
          iconUrl: wikiSite.icon,
          createdAt: DateTime.now(),
          updatedAt: DateTime.now(),
        );
        
        await _databaseService.addFavorite(favorite);
        Get.snackbar(
          '添加收藏',
          '已收藏 ${wikiSite.name}',
          snackPosition: SnackPosition.BOTTOM,
          duration: const Duration(seconds: 2),
        );
      }
      
      await _loadFavorites();
    } catch (e) {
      print('Error toggling favorite: $e');
      Get.snackbar(
        '操作失败',
        '收藏操作失败，请稍后重试',
        snackPosition: SnackPosition.BOTTOM,
        duration: const Duration(seconds: 2),
      );
    }
  }
  
  // 检查是否已收藏
  bool isFavorited(String wikiId) {
    return favorites.any((fav) => fav.wikiId == wikiId);
  }
  

  
  // 获取搜索建议
  Future<List<String>> getSearchSuggestions(String query) async {
    try {
      return await _searchService.getSearchSuggestions(query);
    } catch (e) {
      print('Error getting search suggestions: $e');
      return [];
    }
  }
}

